var express = require('express');
var app = express();
var https = require('https');
var fs = require('fs');
var path = require('path');
var url = require('url');
// var serveIndex = require('serve-index');

var options = {
  key: fs.readFileSync('./ssl/server-key.pem'),
  cert: fs.readFileSync('./ssl/server-cert.pem'),
  ca: fs.readFileSync('./ssl/ca-cert.pem'),
  passphrase: '123456'
};
// app.use(serveIndex('app/'));
//设置跨域访问
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    // res.header("X-Powered-By",' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

var documentRoot = './app';
var server = https.createServer(options, function(req,res,next){
  // var url = req.url;
  // var file = documentRoot + url;
  var pathname = url.parse(req.url).pathname;
  var file = path.join("./app", pathname);
  var ext = path.extname(file);
  ext = ext ? ext.slice(1) : 'unknown';
  // console.log(ext)
  // console.log(pathname,file);
   fs.readFile( file , function(err,data){
     if(err){
          res.writeHeader(404,{
              'content-type' : 'text/html;charset="utf-8"'
          });
          res.write('<h1>404错误</h1><p>你要找的页面不存在</p>');
          res.end();
        }else{
         //  res.writeHeader(200,{
         //     'content-type' : types[ext]
         // });
         // console.log(data);
         res.write(data);//将index.html显示在客户端
         res.end();
        }

   })
  // res.writeHead(200);
  // res.end();
}).listen(3000,'172.18.4.45');
console.log("The HTTPS server is up and running, open https://172.18.4.45:3000/index.html");

var types = {
    "css": "text/css",
    "gif": "image/gif",
    "html": 'text/html;charset="utf-8"',
    "ico": "image/x-icon",
    "jpeg": "image/jpeg",
    "jpg": "image/jpeg",
    "js": "text/javascript",
    "json": "application/json",
   "pdf": "application/pdf",
   "png": "image/png",
   "svg": "image/svg+xml",
   "swf": "application/x-shockwave-flash",
   "tiff": "image/tiff",
   "txt": "text/plain",
   "wav": "audio/x-wav",
   "wma": "audio/x-ms-wma",
   "wmv": "video/x-ms-wmv",
   "xml": "text/xml"
};
